package cn.edu.sdjzu.service.impl;

import cn.edu.sdjzu.dao.SchoolDao;
import cn.edu.sdjzu.entity.School;
import cn.edu.sdjzu.exception.BaseException;
import cn.edu.sdjzu.factory.DaoFactory;
import cn.edu.sdjzu.factory.ServiceFactory;
import cn.edu.sdjzu.service.DepartmentService;
import cn.edu.sdjzu.service.SchoolService;
import cn.edu.sdjzu.util.Condition;
import cn.edu.sdjzu.util.JdbcHelper;
import cn.edu.sdjzu.util.Pagination;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

/**
 * @author 刘永渠
 * @project xg22
 * @date 2024/3/27
 */
public class SchoolServiceImpl implements SchoolService {
    SchoolDao schoolDao = DaoFactory.getDao(SchoolDao.class, "SchoolDaoImpl");
    public boolean add(School school) throws SQLException {
        //获取数据库连接
        Connection connection = JdbcHelper.getConn();
        boolean added = schoolDao.add(connection, school);
        //关闭数据连接
        JdbcHelper.close(connection);
        return added;
    }
    @Override
    public Collection<School> findAll(Pagination pagination) throws SQLException, BaseException {
        return DaoFactory.getDao(SchoolDao.class,"SchoolDaoImpl").findAll(pagination);
    }

    @Override
    public Collection<School> findAll(Pagination pagination, List<Condition> conditionList) throws SQLException, BaseException {
        return DaoFactory.getDao(SchoolDao.class,"SchoolDaoImpl").findAll();
    }

    @Override
    public Collection<School> findAll() throws SQLException, BaseException {
        return DaoFactory.getDao(SchoolDao.class,"SchoolDaoImpl").findAll();
    }

    @Override
    public School find(Integer id) throws SQLException, BaseException {
        return DaoFactory.getDao(SchoolDao.class,"SchoolDaoImpl").find(id);
    }

    @Override
    public boolean delete(Integer id) throws SQLException, BaseException, InvocationTargetException {
        School schoolToDelete = ServiceFactory.getService(SchoolService.class,"SchoolServiceImpl").find(id);
        //获得所有下一级单位（Department）的数量
        int countDepartmentsOfSchool =
                ServiceFactory.getService(DepartmentService.class,"DepartmentService").countAll(schoolToDelete);
        //若没有二级单位，则能够删除
        if(countDepartmentsOfSchool==0){
            return DaoFactory.getDao(SchoolDao.class,"SchoolDaoImpl").delete(id);
        }else {
            throw new BaseException(schoolToDelete.getDescription() + "仍然有下属系，不能删除");
        }
    }
}
